using Ln.Fram.Ddd.Application;
using Ln.Fram.SqlSugarCore.Abstractions;
using Ln.Rbac.Application.Contracts.Dtos.Post;
using Ln.Rbac.Application.Contracts.IServices;
using Ln.Rbac.Domain.Entities;
using Ln.Rbac.Domain.Shared.Consts;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace Ln.Rbac.Application.Services.System;

/// <summary>
/// Post服务实现
/// </summary>
public class PostService : LnCrudAppService<PostAggregateRoot, PostGetOutputDto, PostGetListOutputDto, Guid, PostGetListInputVo, PostCreateInputVo, PostUpdateInputVo>, IPostService
{
	private readonly ISqlSugarRepository<PostAggregateRoot, Guid> _repository;

	public PostService(ISqlSugarRepository<PostAggregateRoot, Guid> repository) : base(repository)
	{
		_repository = repository;
	}

	public override async Task<PagedResultDto<PostGetListOutputDto>> GetListAsync(PostGetListInputVo input)
	{
		RefAsync<int> total = 0;
		var entities = await _repository._DbQueryable.WhereIF(!string.IsNullOrEmpty(input.PostName),
			x => x.PostName.Contains(input.PostName!))
			.WhereIF(input.State is not null, x => x.State == input.State)
			.OrderByDescending(x => x.OrderNum)
			.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
		return new PagedResultDto<PostGetListOutputDto>(total, await MapToGetListOutputDtosAsync(entities));
	}

	protected override async Task CheckCreateInputDtoAsync(PostCreateInputVo input)
	{
		var isExist = await _repository.IsAnyAsync(x => x.PostCode == input.PostCode);
		if (isExist)
			throw new UserFriendlyException(PostConst.Exist);
	}

	protected override async Task CheckUpdateInputDtoAsync(PostAggregateRoot entity, PostUpdateInputVo input)
	{
		var isExist = await _repository._DbQueryable.Where(x => x.Id != entity.Id)
			.AnyAsync(x => x.PostCode == input.PostCode);
		if (isExist)
			throw new UserFriendlyException(RoleConst.Exist);
	}
}